package langchain4j.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import langchain4j.entity.User;
import langchain4j.entity.dto.PasswordUpdateDTO;
import langchain4j.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getUser(@PathVariable("id") Long id) {
        User user = userService.getById(id);

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", user);

        return ResponseEntity.ok(response);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable("id") Long id, @RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        try {
            boolean isUpdated = userService.updateUser(id, user);

            if (isUpdated) {
                response.put("code", 200);
                response.put("message", "用户信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("code", 404);
                response.put("message", "用户不存在或已被删除");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "服务器内部错误");
            return ResponseEntity.internalServerError().body(response);
        }
    }

    @PutMapping("/{id}/password")
    public ResponseEntity<Map<String, Object>> updatePassword(
            @PathVariable("id") Long id,
            @Valid @RequestBody PasswordUpdateDTO dto) {

        Map<String, Object> response = new HashMap<>();
        try {
            boolean success = userService.updatePassword(id, dto);
            response.put("code", success ? 200 : 400);
            response.put("message", success ? "密码修改成功" : "密码验证失败");
            return ResponseEntity.status(success ? 200 : 400).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("message", "服务器错误: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
